<template>
  <div class="home">
    <!-- 头部栏 -->
    <Header></Header>
    <!-- 轮播图 -->
    <section class="banner-box">
      <van-swipe v-if="bannerList.length > 0" autoplay="3000" lazy-render>
        <van-swipe-item v-for="item in bannerList" :key="item.id">
          <router-link :to="`/detail/${item.id}`" class="content">
            <img :src="item.image" alt="" />
            <div class="mark">
              <h3 class="title">{{ item.title }}</h3>
              <span class="tip">{{ item.hint }}</span>
            </div>
          </router-link>
        </van-swipe-item>
      </van-swipe>
    </section>
    <van-button v-show="backTopFlag" icon="back-top" class="backT" color="#7232dd" plain @click="goTop" />
    <!-- 新闻列表 -->
    <div >
      <section class="news-box" v-for="(item, index) in newsList" :key="index">
        <van-divider content-position="left" v-if="index !== 0">
          {{ formatTime(item.date, "{1}月{2}日") }}
        </van-divider>
        <div class="content">
          <Item v-for="item2 in item.stories" :key="item2.id" :data="item2" />
        </div>
      </section>
    </div>
    <div class="lazy-more" v-show="newsList.length !== 0" ref="loadMore">
      <van-loading size="12px">小主，精彩数据准备中...</van-loading>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import Header from '@/components/HelloWorld.vue'
import Item from '@/components/Item.vue'
import { onBeforeMount, reactive, toRefs, onMounted, ref, onUnmounted } from 'vue'
import { formatTime } from "@/assets/utils";
import api from '@/api/baseApi'

export default {
  name: 'HomeView',
  components: {
    Header,
    Item
  },
  setup(){
    // 定义数据
    let state = reactive({
      today: '',
      newsList: [],
      bannerList: [],

    })
    let backTopFlag = ref(false)
    let loadMore = ref(null)
    onBeforeMount(async () => {
      const { date, stories, top_stories} = await api.queryNewsLatest()
      state.today = date
      // 由于新闻列表是不断增加的，所以要push
      state.newsList.push(Object.freeze({
        date, stories
      }))
      state.bannerList = Object.freeze(top_stories)
    })
    // 第一次渲染完:加载更多数据
    onMounted(() => {
      // 浏览器内置方法 IntersectionObserver，返回值是一个观察器实例，可以指定观察哪个 DOM 节点，这里观察的是loadMore节点
      let ob = new IntersectionObserver(async (changes) => {
        // console.log(changes);
        let item = changes[0];
        if (item.isIntersecting) {
          let result = await api.queryNewsBefore(
            state.newsList[state.newsList.length - 1]["date"]
          );
          state.newsList.push(Object.freeze(result));
        }
      });
      // console.log(loadMore);
      ob.observe(loadMore.value);
    });
    const goTop = () => {
      let top = document.documentElement.scrollTop//获取点击时页面的滚动条纵坐标位置
      console.log(top);
      const timeTop = setInterval(() => {
        document.documentElement.scrollTop = top -= 50//一次减50往上滑动
        if (top <= 0) {
          clearInterval(timeTop)
        }
      }, 5)//定时调用函数使其更顺滑
    }
    onMounted(() => {
      window.addEventListener('scroll', handleScroll)
    })//监听滚动事件
    onUnmounted(() => {
      window.removeEventListener('scroll', handleScroll)
    })//离开页面时移除监听事件
    const handleScroll = () => {
      if (document.documentElement.scrollTop > 700) {
        backTopFlag.value = true
      } else {
        backTopFlag.value = false
      }
      //往下滑超过20则显示 否则则不显示按钮
    }
    return {
      ...toRefs(state),
      formatTime,
      loadMore,
      goTop,
      backTopFlag
    }
  }
}
</script>

<style lang="less" scoped>
.home{
  height: 100vh;
  .backT{
    width: 30px;
    height: 35px;
    position: fixed;
    right: 25px;
    bottom: 100px;
    z-index: 200;
  }
}
.banner-box {
  height: 375px;
  box-sizing: border-box;
  background: #d5d5d5;
  .van-swipe {
    height: 100%;
    background: #fff;
    .content{
      position: relative;
      display: block;
      height: 100%;
      color: #fff;

      img{
        width: 100%;
        height: 100%;
        display: block;
      }

      .mark{
        position: absolute;
        bottom: 0;
        left: 0;
        box-sizing: border-box;
        padding: 10px 20px;
        width: 100%;
        height: 110px;
        background: rgba(0, 0, 0, 0.3);
        background: -webkit-linear-gradient(
          top,
          rgba(0, 0, 0, 0),
          rgba(0, 0, 0, 0.5)
        );
        .title{
          padding-top: 10px;
          max-height: 50px;
          font-size: 20px;
          line-height: 25px;
          overflow: hidden;
        }
        .tip {
          font-size: 12px;
          line-height: 20px;
        }
      }
    }
    /deep/ .van-swipe__indicators {
      left: auto;
      right: 15px;
      transform: none;

      .van-swipe__indicator--active {
        width: 15px;
        border-radius: 3px;
        background: #fff;
      }
    }
  }
}
.news-box{
  padding: 0 15px;
  .van-divider {
    margin: 5px 0;
    font-size: 12px;

    &:before {
      display: none;
    }
  }
}
.lazy-more {
  display: flex;
  justify-content: center;
  padding: 10px;
  background: #f4f4f4;
}
</style>
